// searchPayload.ts
import pinyin from 'pinyin';

export interface Movie {
  name: string;
  [key: string]: any;
}

export interface SearchPayload {
  items: Movie[];
  query: string;
}

/**
 * 支持汉字、拼音全拼、首字母搜索
 */
export function filterMoviesByPinyin({ items, query }: SearchPayload): Movie[] {
  if (!query) return items;

  const lowerQuery = query.toLowerCase();

  return items.filter(item => {
    const name = item.name.toLowerCase();

    // 1. 直接匹配汉字
    if (name.includes(lowerQuery)) return true;

    // 2. 全拼匹配
    const fullPinyin = pinyin(item.name, { style: pinyin.STYLE_NORMAL })
      .flat()
      .join('');
    if (fullPinyin.includes(lowerQuery)) return true;

    // 3. 首字母匹配
    const initials = pinyin(item.name, { style: pinyin.STYLE_FIRST_LETTER })
      .flat()
      .join('');
    if (initials.includes(lowerQuery)) return true;

    return false;
  });
}
